﻿using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQDemo.DelayQueue.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;

namespace RabbitMQDemo.DelayQueue.Producer
{
    public class MessageProducerService : ITransientDependency
    {
        public  void Run()
        {
            using (var connection = new ConnectionFactory().CreateConnection())
            {
                Console.WriteLine("输入任意键发送测试消息");
                while (Console.ReadLine() != null)
                {
                    using (var channel = connection.CreateModel())
                    {

                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        dic.Add("x-expires", 30000);
                        dic.Add("x-message-ttl", 5000);//队列上消息过期时间，应小于队列过期时间 
                        dic.Add("x-dead-letter-exchange", "exchange-direct");//过期消息转向路由 
                        dic.Add("x-dead-letter-routing-key", "routing-delay");//过期消息转向路由相匹配routingkey 
                                                                              //创建一个名叫"zzhello"的消息队列
                        channel.QueueDeclare(queue: "zzhello",
                          durable: true,
                          exclusive: false,
                          autoDelete: false,
                          arguments: dic);
                        MessageEntity messageEntity = new MessageEntity();
                        messageEntity.Body = "this is a test msg";
                        var message = JsonConvert.SerializeObject(messageEntity);
                        //var message = "this is a test msg";
                        var body = Encoding.UTF8.GetBytes(message);

                        //向该消息队列发送消息message
                        channel.BasicPublish(exchange: "",
                          routingKey: "zzhello",
                          basicProperties: null,
                          body: body);
                        Console.WriteLine(" Producer Sent message:{0},time:{1}", message, DateTime.Now);
                    }
                }
            }
        }
    }
}
